<template>
  <div class="full-box">
    <el-row class="row1">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item><a>订单管理</a></el-breadcrumb-item>
        <el-breadcrumb-item>订单商品添加</el-breadcrumb-item>
      </el-breadcrumb>
    </el-row>
    <el-row class="buttonGroup">
      <el-button-group>
        <el-button type="warning" @click="certainProduct">
          结算
        </el-button>
      </el-button-group>
    </el-row>
    <el-row class="table">
      <el-table
          :data="productList"
          @selection-change="handleSelectionChange">
        <el-table-column type="selection"></el-table-column>
        <el-table-column prop="nickName" label="通用名" show-overflow-tooltip></el-table-column>
        <el-table-column prop="productName" label="商品名" show-overflow-tooltip></el-table-column>
        <el-table-column prop="unit" label="包装规格"></el-table-column>
        <el-table-column prop="suppliers" label="生产厂家" show-overflow-tooltip></el-table-column>
        <el-table-column prop="classs" label="产品批号"></el-table-column>
        <el-table-column prop="type" label="剂型"></el-table-column>
        <el-table-column prop="price" label="价格"></el-table-column>


        <el-table-column label="操作" width="300px" align="center">
          <template #default="scope">
            <el-input-number v-model="scope.row.num" size="small">

            </el-input-number>
          </template>
        </el-table-column>
      </el-table>
      <el-row style="width: 100%; display: flex;justify-content: right">
        <el-pagination
            style="margin-top: 10px"
            v-model:current-page="data.stockPage.currentPage"
            @current-change="handleCurrentChangeClient"
            layout="prev, pager, next"
            :page-size="5"
            :total="data.stockPage.total"
        />
      </el-row>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
import {reactive, onMounted, ref} from "vue";
import axios from "axios";
import moment from "moment";
import router from "@/router";
import {ElMessage} from "element-plus";

// 定义一个接口来表示订单详情的结构
interface OrderDetail {
  detailId: string;
  orderId: string;
  productId: number;
  quantity: number;
}

//定义产品结构
interface ProductItem {
  productId: number;
  nickName: string;
  productName: string;
  unit: string;
  suppliers: string;
  classId: number;
  typeId: number;
  stockCount: number;
  price: number;
  classs: string;
  type: string;
  num: number;
}

let productList = ref<ProductItem[]>([]);
let productList2 = ref<ProductItem[]>([]);

const data = reactive({
  list: [],
  stockPage: {
    currentPage: 1,
    total: ""
  },
  addProduct: {
    productId: "",
    quantity: ""
  },
  key: "",//要添加商品的orderId
  loading: {
    loadingId: "",
    orderId: "",
    loader: "",
    creTime: "",
    endTime: ""
  }//loading添加信息

})


onMounted(() => {
  getOrderId();
  handleCurrentChangeStock();
})
//list信息
const handleCurrentChangeStock = () => {
  axios({
    url: "http://localhost:8080/productView/selectAll",
    method: "get",
    params: {
      currentPage: data.stockPage.currentPage
    }
  }).then((res) => {
    productList = res.data.data;
    console.log(data.list);
    data.stockPage.total = res.data.total;
  })
}

const test = (row: any) => {
  console.log(row.stockCount);
  // insertNew();
}
//获得多选框信息
const handleSelectionChange = (val: ProductItem[]) => {
  console.log(val.length);
  productList2.value = val;
  console.log(productList2);
}

//成功消息
const successMessage = (message: any) => {
  ElMessage({
    showClose: true,
    message: message,
    type: 'success',
  });
}
//失败消息
const errorMessage = (message: any) => {
  ElMessage({
    showClose: true,
    message: message,
    type: 'error',
  });
}

// 读取并显示 sessionStorage 中的数据
const getOrderId = () => {
  const orderId = sessionStorage.getItem("orderId");
  const creTime = sessionStorage.getItem("creTime");

  if (creTime !== null) {
    data.loading.creTime = creTime;
  } else {
    // 处理null的情况，例如抛出一个错误或设置一个默认值
    errorMessage("创建时间为空");
  }

  if (orderId) {
    data.key = orderId; // 正确地更新 reactive 对象的属性
    console.log("OrderId：" + orderId); // 打印从 sessionStorage 获取的 orderId
  } else {
    console.log("No orderId found in sessionStorage");
  }
};

//结算
let certainProduct = () => {
  // 使用接口来声明 orderDetailsList，并指定其元素类型为 OrderDetail
  let orderDetailsList: OrderDetail[] = [];
  for (var i = 0; i < productList2.value.length; i++) {
    const orderDetail = {
      detailId: "",
      orderId: "",
      productId: 0,
      quantity: 0
    }//获取选定商品列表
    orderDetail.orderId = data.key;
    orderDetail.productId = productList2.value[i].productId;
    orderDetail.quantity = productList2.value[i].num;
    orderDetailsList.push(orderDetail);
  }
  //给订单添加商品
  axios({
    url: "http://localhost:8080/OrderDetails/test", // 只需要资源路径
    method: "post", // 使用POST方法
    data: orderDetailsList
  }).then(response => {
    if (response.data.success) {
      successMessage("创建成功");
      creLoading();
      router.push("/loading/fullFront");
    } else {
      errorMessage("创建失败");
    }
    // 处理响应
    console.log(response.data);
  }).catch(error => {
    // 处理错误
    console.error(error);
  });

}


//  创建装配单
const creLoading = () => {
  data.loading.endTime = moment(new Date()).format(' YYYY-MM-DD HH:mm');
  data.loading.orderId = data.key;
  axios({
    url: "http://localhost:8080/loading2/save", // 只需要资源路径
    method: "post", // 使用POST方法,
    params: data.loading
  }).then((res) => {
    if (res.data.success) {
    } else {
      errorMessage("创建配送单失败");
    }
  })
}

</script>

<style scoped>
.full-box {
  margin: 15px;
  width: 100%;
  height: 100vh;
}

.table {
  margin-top: 20px;
}

.buttonGroup {
  margin-top: 20px;

}
</style>